import SlsTracker from '@aliyun-sls/web-track-browser';
import { getToken, getUserId } from '@utils/StorageManager';

const opts = {
    host: 'eu-central-1.log.aliyuncs.com', // 所在地域的服务入口。例如cn-hangzhou.log.aliyuncs.com
    project: 'Kumianmei-prod-frankfurt', // Project名称。
    logstore: 'Kumianmei-h5', // Logstore名称。
    time: 5, // 发送日志的时间间隔，默认是10秒。
    count: 10, // 发送日志的数量大小，默认是10条。
    source: 'h5-app',
};

let logger = null;
let reporting = false;

const ALiLog = {
    send: (LogObject, topic, logLevel, now = false) => {
        if (import.meta.env.MODE === 'production' && !reporting) {
            logger = new SlsTracker({
                topic, // 自定义日志主题。
                ...opts,
            });
            const LogInfo = {
                userId: getUserId() || 'Unknown',
                reportTime: new Date().toString(),
                __log_level: logLevel,
                Env: '正式环境',
                ...LogObject,
            };
            if (now) {
                logger.sendImmediate(LogInfo);
            } else {
                logger.send(LogInfo);
            }
            reporting = true;
            setTimeout(() => {
                reporting = false;
            }, 3000);
        } else {
            console.info('非正式环境不发送日志');
        }
    },
    sendBatch: (LogObjectArray, topic, logLevel, now = false) => {
        if (import.meta.env.MODE === 'production' && !reporting) {
            logger = new SlsTracker({
                topic, // 自定义日志主题。
                ...opts,
            });
            const userId = getUserId() || 'Unknown';
            const time = new Date().toString();
            const arr = LogObjectArray.map((item) => {
                item.userId = userId;
                item.reportTime = time;
                item.__log_level = logLevel;
                return item;
            });
            if (now) {
                logger.sendBatchLogsImmediate(arr);
            } else {
                logger.sendBatchLogs(arr);
            }
            reporting = true;
            setTimeout(() => {
                reporting = false;
            }, 3000);
        } else {
            console.info('非正式环境不发送日志');
        }
    },

    reportRoute: (path = '', reason = '', to404 = false) => {
        ALiLog.send(
            {
                action: to404 ? '导航至404' : '访问路由',
                path,
                url: window.location.href,
                to404,
                reason,
                userId: getUserId(),
                token: getToken(),
            },
            '访问路由',
            'Info'
        );
    },
};

export default ALiLog;
